package com.xiaomili.halfsugar.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.AppBarLayout.OnOffsetChangedListener;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.xiaomili.halfsugar.R;
import com.xiaomili.halfsugar.activity.GuideActivity;
import com.xiaomili.halfsugar.adapter.RecyclerViewAdapter;
import com.xiaomili.halfsugar.adapter.RecyclerViewAdapter.onItemClickListener;
import com.xiaomili.halfsugar.bean.ArticleBean;
import com.xiaomili.halfsugar.bean.LatestBean;
import com.xiaomili.halfsugar.bean.LatestBean.DataBean.TopicBean;
import com.xiaomili.halfsugar.constant.UrlString;
import com.xiaomili.halfsugar.utils.LogUtils;
import com.xiaomili.halfsugar.utils.OKHttpUtils;
import com.xiaomili.halfsugar.utils.OKHttpUtils.MyCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * A simple {@link Fragment} subclass.
 */
public class ArticleFragment extends Fragment implements OnCheckedChangeListener {
    private static final String TAG = "ArticleFragment";
    @InjectView(R.id.rg_container)
    RadioGroup mRgContainer;
    @InjectView(R.id.iv_social_guide)
    ImageView mIvSocialGuide;
    @InjectView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @InjectView(R.id.ptr_refresh)
    PtrClassicFrameLayout mPtrRefresh;
    @InjectView(R.id.appBarLayout)
    AppBarLayout mAppBarLayout;

    private Context mContext;
    private List<TopicBean> mDatas;


    public ArticleFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDatas = new ArrayList<>();
        mContext = getActivity();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_article, container, false);
        ButterKnife.inject(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPtrRefresh.post(new Runnable() {
            @Override
            public void run() {
                mPtrRefresh.autoRefresh();
            }
        });
        //设置顶部RadioButton点击事件
        mRgContainer.setOnCheckedChangeListener(this);
        //加载中间精选原创的图片
        loadData();
        mPtrRefresh.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //设置recyclerview适配器
                loadRecyclerViewData();
                mPtrRefresh.refreshComplete();
            }
        });


        //如果AppBarLayout相对于顶部的偏移量小于0则不刷新,否则刷新
        if (mAppBarLayout != null) {
            mAppBarLayout.addOnOffsetChangedListener(new OnOffsetChangedListener() {
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    if (mPtrRefresh == null) return;
                    mPtrRefresh.setEnabled(verticalOffset >= 0 ? true : false);
                }
            });
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, final int checkedId) {
        RadioButton rb = (RadioButton) group.findViewById(checkedId);
        rb.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO button点击跳转界面实现()
                Toast.makeText(mContext, "你点击了第几" + checkedId + "个bt", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //加载原创精选的网络数据
    private void loadData() {
        OKHttpUtils.newInstance(mContext).obtainDataAsyncByGet(UrlString.COMMUNITY_CREATE_URL, new MyCallback() {
            @Override
            public void onFailure(IOException e) {
                LogUtils.i("网络连接失败");
            }

            @Override
            public void onResponse(String result) {
                LogUtils.i("线程类型?-->" + Thread.currentThread().getName());
                final ArticleBean articleBean = new Gson().fromJson(result, ArticleBean.class);
                Picasso.with(mContext).load(articleBean.data.insert_element.get(0).photo).into(mIvSocialGuide);
                mIvSocialGuide.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GuideActivity.toGuideActivity(mContext, articleBean.data.insert_element.get(0).title,
                                articleBean.data.insert_element.get(0).extend);
                    }
                });

            }
        });
    }

    //加载recyclerview的网络数据
    private void loadRecyclerViewData() {
        OKHttpUtils.newInstance(mContext).obtainDataAsyncByGet(UrlString.COMMUNITY_TOPIC_URL, new MyCallback() {
            @Override
            public void onFailure(IOException e) {
                LogUtils.i("网络连接失败");
            }

            @Override
            public void onResponse(String result) {
                LatestBean latestBean = new Gson().fromJson(result, LatestBean.class);
                mDatas.addAll(latestBean.data.topic);
                RecyclerViewAdapter adapter = new RecyclerViewAdapter(mContext);
                adapter.setData(mDatas);
                mRecyclerView.setAdapter(adapter);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
                adapter.setOnItemClickListener(new onItemClickListener() {
                    @Override
                    public void onClick(View view, int position) {
                        //TODO recyclerview单项点击跳转界面
                        Toast.makeText(mContext, "你点击了" + position + "位置", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


}

